package com.lianyi.push.share.udpservice;

import android.content.Context;

import com.lianyi.push.share.ConstantValue;
import com.lianyi.push.share.listener.UdpClientToSeiviceMessageListener;
import com.lianyi.push.util.Preconditions;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

/**
 * Created by leilei on 2018/4/8.
 */

public class UdpService {
    private Context mContext;
    private ExecutorService executorService = Executors.newFixedThreadPool(ConstantValue.TCP_MAX_COUNT);
    private UdpClientToSeiviceMessageListener udpClientToSeiviceMessageListener;

    private UdpService() {
    }

    public void init(Context context) {
        this.mContext = context;
    }

    private static class SingletonHolder {
        private static final UdpService INSTANCE = new UdpService();
    }

    public static UdpService getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public synchronized void StartUdpService(UdpClientToSeiviceMessageListener listener) {
        Preconditions.checkNotNull(mContext, "UdpService StartUdpService Context is Null!");
        Preconditions.checkNotNull(listener, "UdpService StartUdpService UdpClientToSeiviceMessageListener is Null!");
        this.udpClientToSeiviceMessageListener = listener;
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                UdpService.getInstance().StartService();
            }
        });
    }

    public void StartService() {
        EventLoopGroup group = null;
        try {
            group = new NioEventLoopGroup();
            Bootstrap b = new Bootstrap();//udp不能使用ServerBootstrap
            b.group(group).channel(NioDatagramChannel.class)//设置UDP通道
                    .option(ChannelOption.SO_BROADCAST, true)// 支持广播
                    .handler(new UdpServerHandler(mContext, udpClientToSeiviceMessageListener));
            System.out.println("[UDP 启动了]");
            b.bind(ConstantValue.UDP_PORT).sync().channel().closeFuture().await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//            try {
                if (group != null) {
                    group.shutdownGracefully();
                    System.out.println("[UDP 关闭了]");
                }
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
    }
}
